package com.kiln.juxingqs.ui.socket

import android.os.Bundle
import android.widget.Button
import android.widget.TextView
import androidx.appcompat.app.AppCompatActivity
import com.kiln.juxingqs.R
import okhttp3.*
import okio.ByteString

class WebSocketActivity3 : AppCompatActivity() {

    private lateinit var client: OkHttpClient
    private var startButton: Button? = null
    private var outputText: TextView? = null


    private inner class EchoWebSocketListener : WebSocketListener() {
        private var NORMAL_CLOSURE_STATUS: Int = 1000

        override fun onOpen(webSocket: WebSocket, response: Response) {
            webSocket.send("Hola there!")
            webSocket.send("cool")
            webSocket.close(NORMAL_CLOSURE_STATUS,"GoodBye!!")
        }

        override fun onMessage(webSocket: WebSocket, bytes: ByteString) {
            output("Receiving "+ bytes.toString())
        }

        override fun onClosing(webSocket: WebSocket, code: Int, reason: String) {
            webSocket.close(NORMAL_CLOSURE_STATUS, null)
            output("Closing : "+ code + "/" + reason)
        }

        override fun onFailure(webSocket: WebSocket, t: Throwable, response: Response?) {
            output("Error : " + t.message)
        }
    }

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        setContentView(R.layout.activity_ws)
        startButton = findViewById<Button>(R.id.tv_start)
        outputText = findViewById<TextView>(R.id.tv_output)
        client = OkHttpClient()
        startButton!!.setOnClickListener{
            start()
        }
    }

    private fun start() {
        val request: Request = Request.Builder().url("http://192.168.0.66:5000/test").build()
        val listener: EchoWebSocketListener = EchoWebSocketListener()
        val ws: WebSocket = client.newWebSocket(request, listener)
        client.dispatcher.executorService.shutdown()
    }

    private fun output(s: String) {
        runOnUiThread({
            object : Runnable {
                override fun run() {
                    outputText!!.setText(outputText!!.text.toString() + "\n\n" + s)
                }
            }
        })
    }

}